﻿using System;
using System.Diagnostics;
using System.Linq;
using Cav;
using Cav.WinForm.BaseClases;
using Nefela.BusinessLogic;
using Nefela.CommonTypes;

namespace Nefela.UI
{
    public partial class ucFillDocs : UserControlBase
    {
        public ucFillDocs()
        {
            InitializeComponent();
            dgwFCCUserInput.AutoGenerateColumns = false;
        }

        SettingsBL setBL;
        CustomerCardBL ccardBL;

        private void btFillDoc_Click(object sender, EventArgs e)
        {
            var pds = cbCustomerForFill.SelectedItem as CustomerCardType;
            if (pds == null)
                return;

            if (setBL.ModelPackegeDocs.OutputDir.IsNullOrWhiteSpace())
            {
                Dialogs.ErrorF(this, "Не наcтроен выходной каталог");
                return;
            }

            try
            {
                DocumentBL docBL = new DocumentBL();
                docBL.FillDocument(pds, setBL.ModelPackegeDocs);

                Dialogs.InformationF(this, "Готово");
            }
            catch (Exception ex)
            {
                Dialogs.ErrorF(this, ex.Expand());
            }
        }
        private void cbDocForFill_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbCustomerForFill.SelectedItem == null)
            {
                dgwFCCUserInput.DataSource = null;
                if (cbCustomerForFill.Items.Count > 0)
                    cbCustomerForFill.SelectedIndex = 0;
                return;
            }

            var fiu = ((CustomerCardType)cbCustomerForFill.SelectedItem).Fields.Where(x => x.FieldCardCustomer.UserInput).ToList();
            if (fiu.Count == 0)
                dgwFCCUserInput.DataSource = null;
            else
                dgwFCCUserInput.DataSource = fiu;
        }

        private void ucFillDocs_Load(object sender, EventArgs e)
        {
            if (this.IsDesignMode)
                return;

            setBL = (SettingsBL)this.BusinessLogic;
            ccardBL = new CustomerCardBL();
            ccardBL.LoadCards();

            cbCustomerForFill.DataSource = ccardBL.ModelCards;
            cbCustomerForFill.DisplayMember = "Name";

            dgwFCCUserInput.AutoGenerateColumns = false;

            cbDocForFill_SelectedIndexChanged(null, null);
        }

        public override void RefreshControl()
        {
            base.RefreshControl();

            ccardBL.LoadCards();
        }

        private void ucFillDocs_HelpRequested(object sender, System.Windows.Forms.HelpEventArgs hlpevent)
        {
            Process.Start("https://goo.gl/0oP2pZ");
        }
    }
}
